<?php
/**
 *CouponServices
 * @author tan bing
 * @date 2021-10-11 15:29
 */


namespace Modules\Coupon\Services\Api;


use App\Extend\Random;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Coupon\Entities\UserCoupon;
use Modules\Coupon\Repositories\Contracts\CouponInterface;

class CouponServices extends BaseService
{

    /**
     * @var CouponInterface
     * @author tan bing
     */
    private CouponInterface $couponInterface;

    /**
     * @var Request
     * @author tan bing
     */
    private Request $request;

    /**
     * CouponServices constructor.
     *
     * @param Request $request
     * @param CouponInterface $couponInterface
     * @author tan bing
     * @date 2021-10-14 11:14
     */
    public function __construct(Request $request, CouponInterface $couponInterface)
    {
        $this->request = $request;
        $this->couponInterface = $couponInterface;
    }

    /**
     * 获取优惠券列表.
     * @return array
     * @author tan bing
     * @date 2021-10-11 17:12
     */
    public function getCouponList()
    {
        $param = $this->request->input();
        $param['status'] = 1;
        $query = $this->couponInterface->getPageData($param, $this->perPage());
        $data = $query->items();
        $count = $query->total();

        foreach ($data as $k => $v) {
            $data[$k]['is_receive'] = 0;
            $data[$k]['start_time'] = $v['start_time'] ? date('Y-m-d H:i:s', $v['start_time']) : '';
            $data[$k]['end_time'] = $v['end_time'] ? date('Y-m-d H:i:s', $v['end_time']) : '';
            if($this->request->attributes->get('userId')) {
                $userCoupon = UserCoupon::query()->where(['user_id' => $this->request->attributes->get('userId'), 'coupon_id' => $v->id])->first();
                if($userCoupon) $data[$k]['is_receive'] = 1;
            }
        }
        return compact('count', 'data');
    }

    /**
     * 领取优惠券
     * @return array
     * @throws \Throwable
     * @author tan bing
     * @date 2021-10-14 15:28
     */
    public function receiveCoupon()
    {
        $param = $this->request->input();
        $couponId = $this->request->post('coupon_id');
        $userId   = $this->request->attributes->get('userId');
        try {
            DB::beginTransaction();
            $coupon = $this->couponInterface->findById($couponId);
            if (!$coupon) throw new \Exception('Request Param Error.');
            if ($coupon->total_num > 0) {
                if ($coupon->receive_num >= $coupon->total_num)
                    throw new \Exception('手慢了，优惠券数量已发放完');
            }
            $userCoupon      = new UserCoupon();
            $userCouponCount = UserCoupon::query()->where(['user_id'   => $userId, 'coupon_id' => $couponId])->count();
            if ($userCouponCount >= $coupon->max_receive_num)
                throw new \Exception('领取超限，每人最多领取' . $coupon->max_receive_num . '张');

            if($coupon->expire_type == 1) {
                $start_time = time();
                $end_time = strtotime(date('Y-m-d H:i:s', strtotime('7 day')));
            } else {
                $start_time = $coupon->start_time;
                $end_time = $coupon->end_time;
            }
            $userCoupon->user_id            = $userId;
            $userCoupon->coupon_id          = $couponId;
            $userCoupon->coupon_code        = Random::alnum(10);
            $userCoupon->coupon_name        = $coupon->coupon_name;
            $userCoupon->coupon_type        = $coupon->coupon_type;
            $userCoupon->is_use             = 0;
            $userCoupon->is_expire          = 0;
            $userCoupon->reduce_price       = $coupon->reduce_price;
            $userCoupon->discount           = $coupon->discount;
            $userCoupon->min_price          = $coupon->min_price;
            $userCoupon->expire_type        = $coupon->expire_type;
            $userCoupon->expire_day         = $coupon->expire_day;
            $userCoupon->start_time         = $start_time;
            $userCoupon->end_time           = $end_time;
            $userCoupon->apply_range        = $coupon->apply_range;
            $userCoupon->apply_range_config = $coupon->apply_range_config;
            if (!$userCoupon->save())
                throw new \Exception('优惠券领取失败');

            $coupon->receive_num = $coupon->receive_num + 1;
            if (!$coupon->save())
                throw new \Exception('领取失败');

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }

        $coupon_list = $this->getCouponList()['data'];

        return compact('userCoupon', 'coupon_list');
    }

    /**
     * 获取用户优惠券列表
     * @return array
     * @author tan bing
     * @date 2021-10-14 15:41
     */
    public function getUserCouponList()
    {
        $param = $this->request->input();
        $param['user_id'] = $this->request->attributes->get('userId');
        $query = $this->couponInterface->getUserCouponList($param, $this->perPage());
        $data = $query->items();
        foreach ($data as &$v) {
            $v['start_time'] = $v['start_time'] ? date('Y-m-d H:i:s', $v['start_time']) : '';
            $v['end_time'] = $v['end_time'] ? date('Y-m-d H:i:s', $v['end_time']) : '';
        }
        $count = $query->total();

        return compact('count', 'data');
    }
}